package com.lottery.system.controller;
import com.lottery.system.common.errorcode.ControllerErrorCodeConstants;
import com.lottery.system.common.exception.ControllerException;
import com.lottery.system.common.pojo.CommonResult;
import com.lottery.system.common.utils.JacksonUtil;
import com.lottery.system.controller.param.CreateActivityParam;
import com.lottery.system.controller.param.PageParam;
import com.lottery.system.controller.result.CreateActivityResult;
import com.lottery.system.controller.result.GetActivityDetailResult;
import com.lottery.system.controller.result.GetActivityListResult;
import com.lottery.system.service.ActivityService;
import com.lottery.system.service.dto.ActivityDetailDTO;
import com.lottery.system.service.dto.ActivityInfoDTO;
import com.lottery.system.service.dto.CreateActivityDTO;
import com.lottery.system.service.dto.PageListDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Comparator;


/**
 * @author: xiaoxie
 * create: 2024-09-09 10:01
 * @BelongsProject: lottery-system
 * @BelongsPackage: com.lottery.system.controller
 * description: 活动控制层
 */
@RestController
public class ActivityController {

    private final static Logger logger = LoggerFactory.getLogger(ActivityController.class);
    @Autowired
    private ActivityService activityService;
    /**
     * @description: 创建活动
     * @author: xiaoxie
     * @date: 2024/9/9 10:21
     * @param: [param]
     * @return: com.lottery.system.common.pojo.CommonResult<com.lottery.system.controller.result.CreateActivityResult>
     **/
    @RequestMapping("/activity/create")
    public CommonResult<CreateActivityResult> createActivity(
            @Validated @RequestBody CreateActivityParam param) {
        logger.info("createActivity param:{}", JacksonUtil.writeValueAsString(param));
        CreateActivityDTO createActivityDTO = activityService.createActivity(param);
        return CommonResult.success(
                convernToCreateActivityResult(createActivityDTO));
    }
    /**
     * @description: 获取活动列表
     * @author: xiaoxie
     * @date: 2024/9/9 21:40
     * @param: [param]
     * @return: com.lottery.system.common.pojo.CommonResult<GetActivityList>
     **/
    @RequestMapping("/activity/getList")
    public CommonResult<GetActivityListResult> getActivityList(PageParam param) {
        logger.info("getActivityList param:{}", JacksonUtil.writeValueAsString(param));
        PageListDTO<ActivityInfoDTO> activityInfoDTO = activityService.getActivityList(param);
        return  CommonResult.success(
                convernToGetActivityListResult(activityInfoDTO)
        );
    }
    /**
     * @description: 获取活动信息信息
     * @author: xiaoxie
     * @date: 2024/9/10 15:43
     * @param: [activityId]
     * @return: com.lottery.system.common.pojo.CommonResult<GetActivityDetailResult>
     **/
    @RequestMapping("/activity-detail/find")
    public CommonResult<GetActivityDetailResult> getActivityDetail(Long activityId) {
        logger.info("getActivityDetail param:{}", activityId);
        ActivityDetailDTO detailDTO = activityService.getActivityDetail(activityId);
        return CommonResult.success(
                convernToGetActivityDetailResult(detailDTO)
        );
    }

    private GetActivityDetailResult convernToGetActivityDetailResult(ActivityDetailDTO detailDTO) {
        if(null == detailDTO) {
            logger.warn(ControllerErrorCodeConstants.GET_ACTIVITY_DETAIL_ERROR.getMsg());
            throw new ControllerException(ControllerErrorCodeConstants.GET_ACTIVITY_DETAIL_ERROR);
        }
        GetActivityDetailResult getActivityDetailResult = new GetActivityDetailResult();
        getActivityDetailResult.setActivityId(detailDTO.getActivityId());
        getActivityDetailResult.setActivityName(detailDTO.getActivityName());
        getActivityDetailResult.setDescription(detailDTO.getDescription());
        getActivityDetailResult.setValid(detailDTO.valid());
        getActivityDetailResult.setActivityPrizeDTO(
                detailDTO.getActivityPrizeDTO()
                         .stream()
                          // 抽奖顺序：一等奖、二、三
                        .sorted(
                                Comparator.comparingInt(activityPrizeDTO->activityPrizeDTO
                                .getPrizeTiers()
                                .getCode()) )
                        .map(
                                aDTO-> {
                                    GetActivityDetailResult.Prize gP = new GetActivityDetailResult.Prize();
                                    gP.setPrizeId(aDTO.getPrizeId());
                                    gP.setDescription(aDTO.getDescription());
                                    gP.setImageUrl(aDTO.getImageUrl());
                                    gP.setName(aDTO.getName());
                                    gP.setPrice(aDTO.getPrice());
                                    gP.setPrizeAmount(aDTO.getPrizeAmount());
                                    gP.setPrizeTierName(aDTO.getPrizeTiers().getMessage());
                                    gP.setValid(aDTO.valid());
                                    return gP;
                                }
                        ).toList()
        );
        getActivityDetailResult.setActivityUserDTO(
              detailDTO.getActivityUserDTO()
                      .stream()
                      .map(
                              aDTO->{
                                  GetActivityDetailResult.User getUser = new GetActivityDetailResult.User();
                                  getUser.setUserId(aDTO.getUserId());
                                  getUser.setUserName(aDTO.getUserName());
                                  getUser.setValid(aDTO.valid());
                                  return getUser;
                              }
                      ).toList()
        );
        return getActivityDetailResult;
    }

    private GetActivityListResult convernToGetActivityListResult(PageListDTO<ActivityInfoDTO> activityInfoDTO){
        if(null == activityInfoDTO){
            logger.error(ControllerErrorCodeConstants.GET_ACTIVITY_LIST_ERROR.getMsg());
            throw new ControllerException(ControllerErrorCodeConstants.GET_ACTIVITY_LIST_ERROR);
        }
        GetActivityListResult getActivityListResult = new GetActivityListResult();
        getActivityListResult.setTotal(activityInfoDTO.getTotal());
        getActivityListResult.setRecords(activityInfoDTO.getPageList().stream()
                                         .map(aRecords -> {
                                          GetActivityListResult.ActivityInfoResult activityList = new GetActivityListResult.ActivityInfoResult();
                                          activityList.setActivityName(aRecords.getActivityName());
                                          activityList.setActivityId(aRecords.getActivityId());
                                          activityList.setDescription(aRecords.getDescription());
                                          activityList.setValid(aRecords.getValid());
                                          return activityList;
                                         }).toList()
        );
        return getActivityListResult;
    }


    private CreateActivityResult convernToCreateActivityResult(CreateActivityDTO createActivityDTO) {
        if(null == createActivityDTO) {
            throw new ControllerException(ControllerErrorCodeConstants.CREATE_ACTIVITY_ERROR);
        }
        CreateActivityResult createActivityResult = new CreateActivityResult();
        createActivityResult.setActivityId(createActivityDTO.getActivityId());
        return createActivityResult;
    }
}
